package thread1;

public class ticket1 {
    public static void main(String[] args) {
        // 启动第二个售票窗口
        TicketMethod1 thread2 = new TicketMethod1();
        thread2.setName("售票窗口2");
        thread2.start();
        // 启动第一个售票窗口
        TicketMethod1 thread1 = new TicketMethod1();
        thread1.setName("售票窗口1");
        thread1.start();



        // 启动第三个售票窗口
        TicketMethod1 thread3 = new TicketMethod1();
        thread3.setName("售票窗口3");
        thread3.setPriority(10);
        thread3.start();
    }
}

class TicketMethod1 extends Thread {
    // 总票数，必须定义为 static，随类只加载一次，因为每新建一个线程，都需要 new 一次 TicketThread
    private static int ticketNum = 100;

    @Override
    public void run() {
        while (ticketNum > 0) {
            handleTicket();
        }
    }

    // 必须设置成 static 的，此时的同步监视器是 TicketMethod1.class
    private static synchronized void handleTicket() {
        if (ticketNum > 0) {
            try {
                yield();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "售出车票，tick号为：" + ticketNum--);

        } else {
           return;
        }
    }
}
